package com.epfresh.supplier.activity.employ;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.AuthAdapter;
import com.epfresh.supplier.entity.AuthEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by shenjie on 2017/9/14.
 */

public class AuthSettingActivity extends BaseActivity implements AdapterView.OnItemClickListener, AuthAdapter.SelectAllImageStatusListener {
    private ListView authLv;
    private AuthAdapter adapter;
    private ArrayList<AuthEntity> posLists;
    private ArrayList<AuthEntity> wholeSaleLists;
    private int current = 0;//0代表pos，1代表wholesale

    private RelativeLayout posContainer, wholeSaleContainer, selectAllContainer;
    private ImageView selectAll;
    private TextView posTv, wholeSaleTv;
    private View posV, wholeSaleV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initAuthData();
        initView();
    }

    private void initView() {
        toolbarTitle.setText("权限设置");
        toolbarTitle.setTextColor(getResources().getColor(R.color.font_color_def));
        float textsize = getResources().getDimension(R.dimen.text_size_max_18);
        final float scale = getResources().getDisplayMetrics().density;
        float size = (textsize / scale + 0.5f);
//        toolbarTitle.setTextSize(size);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        setContentView(R.layout.activity_auth_set);
        authLv = (ListView) findViewById(R.id.auth_list);
        adapter = new AuthAdapter(this, posLists);
        adapter.setListener(this);
        authLv.setAdapter(adapter);
        //authLv.setOnItemClickListener(this);
        posContainer = (RelativeLayout) findViewById(R.id.pos_container);
        posContainer.setOnClickListener(this);
        wholeSaleContainer = (RelativeLayout) findViewById(R.id.wholesale_container);
        wholeSaleContainer.setOnClickListener(this);
        posTv = (TextView) findViewById(R.id.pos_tv);
        posV = findViewById(R.id.pos_v);
        wholeSaleTv = (TextView) findViewById(R.id.wholesale_tv);
        wholeSaleV = findViewById(R.id.wholesale_v);
        selectAllContainer = (RelativeLayout) findViewById(R.id.selectall_container);
        //selectAllContainer.setOnClickListener(this);
        selectAll = (ImageView) findViewById(R.id.selectall_iv);
        selectAll.setOnClickListener(this);
        setSelectImage();

    }

    private int selectPosAllState = 1;
    private int selectAPPAll = 1;

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.pos_container:
                setSelection(0);
                break;
            case R.id.wholesale_container:
                setSelection(1);
                break;
            //case R.id.selectall_container:
            case R.id.selectall_iv:
                if (current == 0) {
                    if (selectPosAllState == 0) {
                        for (AuthEntity item : posLists) {
                            item.setHasAuth(true);
                        }
                        selectPosAllState = 1;
                        selectAll.setImageResource(R.mipmap.switchon);
                    } else {
                        for (AuthEntity item : posLists) {
                            item.setHasAuth(false);
                        }
                        selectPosAllState = 0;
                        selectAll.setImageResource(R.mipmap.switchoff);
                    }
                    adapter.setList(posLists);
                    adapter.notifyDataSetChanged();

                } else {
                    if (selectAPPAll == 0) {
                        for (AuthEntity item : wholeSaleLists) {
                            item.setHasAuth(true);
                        }
                        selectAPPAll = 1;
                        selectAll.setImageResource(R.mipmap.switchon);
                    } else {
                        for (AuthEntity item : wholeSaleLists) {
                            item.setHasAuth(false);
                        }
                        selectAPPAll = 0;
                        selectAll.setImageResource(R.mipmap.switchoff);
                    }
                    adapter.setList(wholeSaleLists);
                    adapter.notifyDataSetChanged();
                }
                break;
        }
    }

    private void setSelection(int select) {
        if (select == 0) {
            current = 0;
            posTv.setTextColor(getResources().getColor(R.color.red));
            posV.setVisibility(View.VISIBLE);
            wholeSaleTv.setTextColor(getResources().getColor(R.color.wholesale));
            wholeSaleV.setVisibility(View.INVISIBLE);
            adapter.setList(posLists);
            adapter.notifyDataSetChanged();
            if (selectPosAllState == 0) {
                selectAll.setImageResource(R.mipmap.switchoff);
            } else {
                selectAll.setImageResource(R.mipmap.switchon);
            }
        } else {
            current = 1;
            posTv.setTextColor(getResources().getColor(R.color.wholesale));
            posV.setVisibility(View.INVISIBLE);
            wholeSaleTv.setTextColor(getResources().getColor(R.color.red));
            wholeSaleV.setVisibility(View.VISIBLE);
            adapter.setList(wholeSaleLists);
            adapter.notifyDataSetChanged();
            if (selectAPPAll == 0) {
                selectAll.setImageResource(R.mipmap.switchoff);
            } else {
                selectAll.setImageResource(R.mipmap.switchon);
            }
        }
    }

    private void initAuthData() {
        if (Constant.posLists != null && Constant.wholeSaleLists != null) {
            posLists = Constant.posLists;
            wholeSaleLists = Constant.wholeSaleLists;
            setSelectAllStatus();
            return;
        }
//        posLists=new ArrayList<>();
//        //spot
//        AuthEntity spot=new AuthEntity();
//        spot.setMenu(1);
//        spot.setMainTitle("现场销售");
//        spot.setId("spot");
//        spot.setVisible(true);
//        spot.setHasAuth(true);
//        posLists.add(spot);
//
//        AuthEntity kaidan=new AuthEntity();
//        kaidan.setMenu(2);
//        kaidan.setId("root.app.pos.order");
//        kaidan.setParentId("spot");
//        kaidan.setMainTitle("开单/挂单");
//        kaidan.setSubTitle("选货开单，处理挂单记录");
//        kaidan.setVisible(true);
//        kaidan.setHasAuth(true);
//        posLists.add(kaidan);
//
//        AuthEntity customer=new AuthEntity();
//        customer.setMenu(2);
//        customer.setId("root.app.pos.customer");
//        customer.setParentId("spot");
//        customer.setMainTitle("客户");
//        customer.setSubTitle("维护客户信息");
//        customer.setVisible(true);
//        customer.setHasAuth(true);
//        posLists.add(customer);
//
//        AuthEntity finance=new AuthEntity();
//        finance.setMenu(1);
//        finance.setId("finance");
//        finance.setMainTitle("财务管理");
//        finance.setVisible(true);
//        finance.setHasAuth(true);
//        posLists.add(finance);
//
//        AuthEntity xiaozhang=new AuthEntity();
//        xiaozhang.setMenu(2);
//        xiaozhang.setId("root.app.pos.write_off");
//        xiaozhang.setMainTitle("销账");
//        xiaozhang.setSubTitle("销客户赊账");
//        xiaozhang.setParentId("finance");
//        xiaozhang.setVisible(true);
//        xiaozhang.setHasAuth(true);
//        posLists.add(xiaozhang);
//
//        AuthEntity taizhang=new AuthEntity();
//        taizhang.setMenu(2);
//        taizhang.setId("root.app.pos.standing_book");
//        taizhang.setMainTitle("台账");
//        taizhang.setSubTitle("查看pos的账本，欠款订单销账");
//        taizhang.setParentId("finance");
//        taizhang.setVisible(true);
//        taizhang.setHasAuth(true);
//        posLists.add(taizhang);
//
//
//
//        wholeSaleLists=new ArrayList<>();
//        ByteArrayOutputStream out=new ByteArrayOutputStream();
//        try {
//            InputStream input=getAssets().open("wholesale.txt");
//            byte[] buffer=new byte[1024];
//            int len=-1;
//            while ((len=input.read(buffer))!=-1){
//                out.write(buffer,0,len);
//            }
//            String s=new String(out.toByteArray(),"UTF-8");
//            JSONArray array=new JSONArray(s);
//            for (int i=0;i<array.length();i++){
//                JSONObject object=array.getJSONObject(i);
//                AuthEntity entity=new AuthEntity();
//                entity.setMenu(object.getInt("menu"));
//                entity.setMainTitle(object.getString("mainTitle"));
//                entity.setSubTitle(object.getString("subTitle"));
//                entity.setId(object.getString("id"));
//                entity.setParentId(object.getString("parentId"));
//                entity.setVisible(object.getBoolean("isVisible"));
//                entity.setHasAuth(object.getBoolean("hasAuth"));
//                wholeSaleLists.add(entity);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            parseResources();
        } catch (JSONException e) {
            e.printStackTrace();
            T.toast("权限获取有误");
            finish();
            return;
        }

        boolean isfromEdit = getIntent().getBooleanExtra("isEdit", false);
        if (isfromEdit && Constant.resources != null) {
            for (AuthEntity entity : posLists) {
                entity.setHasAuth(false);
            }
            for (AuthEntity entity : wholeSaleLists) {
                entity.setHasAuth(false);
            }
            Iterator iterator = Constant.resources.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                for (AuthEntity entity : posLists) {
                    if (key.equals(entity.getId())) {
                        entity.setHasAuth(true);
                        break;
                    }
                }

                for (AuthEntity entity : wholeSaleLists) {
                    if (key.equals(entity.getId())) {
                        entity.setHasAuth(true);
                        break;
                    }
                }
            }
            setAuthStatus();
            setSelectAllStatus();
        }


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (current == 0) {
            AuthEntity select = posLists.get(position);
//            if (select.isHasAuth()) {
//                select.setHasAuth(false);
//                if (select.getMenu() == 1) {
//                    for (AuthEntity item : posLists) {
//                        if (select.getId().equals(item.getParentId())) {
//                            item.setHasAuth(false);
//                        }
//                    }
//                }
//
//            } else {
//                select.setHasAuth(true);
//                if (select.getMenu() == 1) {
//                    for (AuthEntity item : posLists) {
//                        if (select.getId().equals(item.getParentId())) {
//                            item.setHasAuth(true);
//                        }
//                    }
//                }
//
//            }


            if (select.isHasAuth()) {
                select.setHasAuth(false);
                if (select.getMenu() == 1) {
                    for (AuthEntity item : posLists) {
                        if (select.getId().equals(item.getParentId())) {
                            item.setHasAuth(false);
                        }
                    }
                } else {
                    for (AuthEntity item : posLists) {
                        if (select.getParentId().equals(item.getId())) {
                            item.setHasAuth(false);
                        }
                    }
                }

            } else {
                select.setHasAuth(true);
                if (select.getMenu() == 1) {
                    for (AuthEntity item : posLists) {
                        if (select.getId().equals(item.getParentId())) {
                            item.setHasAuth(true);
                        }
                    }
                } else {
                    boolean canSet = true;
                    AuthEntity changeItem = null;
                    for (AuthEntity item : posLists) {
                        if (select.getParentId().equals(item.getId())) {
                            changeItem = item;
                        }
                        if (select.getParentId().equals(item.getParentId())) {
                            if (!item.isHasAuth()) {
                                canSet = false;
                                break;
                            }
                        }
                    }
                    if (changeItem != null) {
                        changeItem.setHasAuth(canSet);
                    }
                }

            }

        } else {
            AuthEntity select = wholeSaleLists.get(position);
//            if (select.isHasAuth()) {
//                select.setHasAuth(false);
//                if (select.getMenu() == 1) {
//                    for (AuthEntity item : wholeSaleLists) {
//                        if (select.getId().equals(item.getParentId())) {
//                            item.setHasAuth(false);
//                        }
//                    }
//                }
//
//            } else {
//                select.setHasAuth(true);
//                if (select.getMenu() == 1) {
//                    for (AuthEntity item : wholeSaleLists) {
//                        if (select.getId().equals(item.getParentId())) {
//                            item.setHasAuth(true);
//                        }
//                    }
//                }
//

//            }
            if (select.isHasAuth()) {
                select.setHasAuth(false);
                if (select.getMenu() == 1) {
                    for (AuthEntity item : wholeSaleLists) {
                        if (select.getId().equals(item.getParentId())) {
                            item.setHasAuth(false);
                        }
                    }
                } else {
                    for (AuthEntity item : wholeSaleLists) {
                        if (select.getParentId().equals(item.getId())) {
                            item.setHasAuth(false);
                        }
                    }
                }

            } else {
                select.setHasAuth(true);
                if (select.getMenu() == 1) {
                    for (AuthEntity item : wholeSaleLists) {
                        if (select.getId().equals(item.getParentId())) {
                            item.setHasAuth(true);
                        }
                    }
                } else {
                    boolean canSet = true;
                    AuthEntity changeItem = null;
                    for (AuthEntity item : wholeSaleLists) {
                        if (select.getParentId().equals(item.getId())) {
                            changeItem = item;
                        }
                        if (select.getParentId().equals(item.getParentId())) {
                            if (!item.isHasAuth()) {
                                canSet = false;
                                break;
                            }
                        }
                    }
                    if (changeItem != null) {
                        changeItem.setHasAuth(canSet);
                    }
                }

            }
        }
        adapter.notifyDataSetChanged();
        setSelectAllStatus();
        setSelectImage();
    }

    @Override
    protected void onDestroy() {
        Constant.posLists = null;
        Constant.wholeSaleLists = null;
        Constant.posLists = posLists;
        Constant.wholeSaleLists = wholeSaleLists;
        super.onDestroy();
    }

    private void parseResources() throws JSONException {
        if (TextUtils.isEmpty(Constant.resourcesStr)) {
            throw new JSONException("权限为空");
        }
        JSONObject object = new JSONObject(Constant.resourcesStr);
        JSONArray posArray = object.getJSONArray("root.app.pos");
        posLists = new ArrayList<>();
        for (int i = 0; i < posArray.length(); i++) {
            JSONObject item = posArray.getJSONObject(i);
            String name = item.getString("name");
            AuthEntity spot = new AuthEntity();
            spot.setMenu(1);
            spot.setId(name);
            spot.setMainTitle(name);
            spot.setVisible(true);
            spot.setHasAuth(true);
            posLists.add(spot);
            JSONArray children = item.getJSONArray("children");
            for (int j = 0; j < children.length(); j++) {
                JSONObject childItem = children.getJSONObject(j);
                AuthEntity kaidan = new AuthEntity();
                kaidan.setMenu(2);
                kaidan.setId(childItem.getString("code"));
                kaidan.setParentId(name);
                kaidan.setMainTitle(childItem.getString("name"));
                kaidan.setSubTitle(childItem.getString("desc"));
                kaidan.setVisible(true);
                kaidan.setHasAuth(true);
                posLists.add(kaidan);
            }
        }

        wholeSaleLists = new ArrayList<>();
        JSONArray wholeArray2 = null;
        try {
            wholeArray2 = object.getJSONArray("root.market");
        } catch (Exception e) {
        }
        if (wholeArray2 != null) {
            for (int i = 0; i < wholeArray2.length(); i++) {
                JSONObject item = wholeArray2.getJSONObject(i);
                String name = item.getString("name");
                AuthEntity spot = new AuthEntity();
                spot.setMenu(1);
                spot.setId(name);
                spot.setMainTitle(name);
                spot.setVisible(true);
                spot.setHasAuth(true);
                wholeSaleLists.add(spot);
                JSONArray children = item.getJSONArray("children");
                for (int j = 0; j < children.length(); j++) {
                    JSONObject childItem = children.getJSONObject(j);
                    AuthEntity kaidan = new AuthEntity();
                    kaidan.setMenu(2);
                    kaidan.setId(childItem.getString("code"));
                    kaidan.setParentId(name);
                    kaidan.setMainTitle(childItem.getString("name"));
                    kaidan.setSubTitle(childItem.getString("desc"));
                    kaidan.setVisible(true);
                    kaidan.setHasAuth(true);
                    wholeSaleLists.add(kaidan);
                }
            }
        }


        JSONArray wholeArray = object.getJSONArray("root.app.supplier");
        for (int i = 0; i < wholeArray.length(); i++) {
            JSONObject item = wholeArray.getJSONObject(i);
            String name = item.getString("name");
            AuthEntity spot = new AuthEntity();
            spot.setMenu(1);
            spot.setId(name);
            spot.setMainTitle(name);
            spot.setVisible(true);
            spot.setHasAuth(true);
            wholeSaleLists.add(spot);
            JSONArray children = item.getJSONArray("children");
            for (int j = 0; j < children.length(); j++) {
                JSONObject childItem = children.getJSONObject(j);
                AuthEntity kaidan = new AuthEntity();
                kaidan.setMenu(2);
                kaidan.setId(childItem.getString("code"));
                kaidan.setParentId(name);
                kaidan.setMainTitle(childItem.getString("name"));
                kaidan.setSubTitle(childItem.getString("desc"));
                kaidan.setVisible(true);
                kaidan.setHasAuth(true);
                wholeSaleLists.add(kaidan);

            }
        }


    }

    private void setAuthStatus() {
        for (int i = 0; i < posLists.size(); i++) {
            AuthEntity item = posLists.get(i);
            if (item.getMenu() == 1) {
                boolean canSet = true;
                for (int j = i + 1; j < posLists.size(); j++) {
                    AuthEntity childItem = posLists.get(j);
                    if (childItem.getMenu() == 1) {
                        break;
                    }
                    if (!childItem.isHasAuth()) {
                        canSet = false;
                        break;
                    }
                }
                item.setHasAuth(canSet);
            }
        }
        for (int i = 0; i < wholeSaleLists.size(); i++) {
            AuthEntity item = wholeSaleLists.get(i);
            if (item.getMenu() == 1) {
                boolean canSet = true;
                for (int j = i + 1; j < wholeSaleLists.size(); j++) {
                    AuthEntity childItem = wholeSaleLists.get(j);
                    if (childItem.getMenu() == 1) {
                        break;
                    }
                    if (!childItem.isHasAuth()) {
                        canSet = false;
                        break;
                    }
                }
                item.setHasAuth(canSet);
            }
        }
    }

    private void setSelectAllStatus() {
        boolean isAll = true;
        for (int i = 0; i < posLists.size(); i++) {
            AuthEntity item = posLists.get(i);
            if (!item.isHasAuth()) {
                isAll = false;
                break;
            }
        }
        if (!isAll) {
            selectPosAllState = 0;
        } else {
            selectPosAllState = 1;
        }
        boolean isAppAll = true;
        for (int i = 0; i < wholeSaleLists.size(); i++) {
            AuthEntity item = wholeSaleLists.get(i);
            if (!item.isHasAuth()) {
                isAppAll = false;
                break;
            }
        }
        if (!isAppAll) {
            selectAPPAll = 0;
        } else {
            selectAPPAll = 1;
        }
    }

    private void setSelectImage() {
        if (current == 0) {
            if (selectPosAllState == 0) {
                selectAll.setImageResource(R.mipmap.switchoff);
            } else {
                selectAll.setImageResource(R.mipmap.switchon);
            }
        } else {
            if (selectAPPAll == 0) {
                selectAll.setImageResource(R.mipmap.switchoff);
            } else {
                selectAll.setImageResource(R.mipmap.switchon);
            }
        }
    }

    @Override
    public void changeStatus() {
        setSelectAllStatus();
        setSelectImage();
    }
}


